import { buildRoutesAction } from "./buildRoutesAction"
import { BuildRoutes } from "@/router/build";
import { ROUTER_HOME_PATH, ROUTER_LOGIN_PATH, ROUTER_ROOT_PATH, ROUTE_NOT_FOUND_NAME } from "@/router/constant";
import { useUserStore } from "@/store/modules/userStore"
import { usePermissionStore } from "@/store/modules/permissionStore";
import { NOT_FOUND_ROUTE } from "@/router/routes/basic";
import type { RouteRecordRaw } from "vue-router";

export function mountRouterGuard() {

    let userStore = useUserStore()
    let perStore = usePermissionStore()
    try {
        BuildRoutes.ROUTER.beforeEach((to, from, next) => {
           

            //如果没有token 跳转登陆页  
            if (!userStore.token) {


                //如果是白名单 直接跳转
                if (BuildRoutes.WHITE_ROUTE_NAME_LIST.includes(to.name as string)) {
                    next()
                    return
                }

                //如果不是白名单 但取消权限校验 直接跳转
                if (to.meta.ignoreAuth) {
                    next();
                    return;
                }

                //保存传参，跳转登录页
                const redirectData: { path: string; replace: boolean; query: Record<string, string> } = {
                    path: ROUTER_LOGIN_PATH,
                    replace: true,
                    query: {
                        original_query: JSON.stringify(to.query),
                        redirect: to.path
                    }
                }
                next(redirectData)
                return
            }

            //有token但去登录页
           if(to.fullPath === ROUTER_LOGIN_PATH){
            next({ path:ROUTER_HOME_PATH, replace: true })
            return
           }
            //如果没有动态挂载路由
            if (!perStore.isDynamicAddedRoute) {
                buildRoutesAction()
                BuildRoutes.ROUTER.addRoute(NOT_FOUND_ROUTE as unknown as RouteRecordRaw)
                next({ ...to, replace: true })
                return
            }

            if (from.query.redirect) {
                const query = from.query
                const nextData = {
                    path: query.redirect,
                    replace: true,
                    query: JSON.parse(query.original_query as string)
                }
                from.query = {}
                next(nextData)
                return
            }

            next()
            return

        })
    } catch (error: any) {
        throw new Error(error.message || error)
    }

}

